import requests
import base64


class BaiDuApi(object):
    def __init__(self, app_key, app_secret):
        self.app_key = app_key
        self.app_secret = app_secret
        self.token = self.access_token(self.app_key, self.app_secret)

    def access_token(self, ak, sk):
        host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={}&client_secret={}'.format(ak, sk)
        response = requests.get(host)
        if response.status_code == 200:
            token = response.json()['access_token']
            return token
        else:
            assert '获取Token失败...'

    def encode(self, img_path):
        with open(img_path, 'rb') as f:
            data = base64.b64encode(f.read())
        return data

    def appearance(self, data, token):
        url = 'https://aip.baidubce.com/rest/2.0/face/v3/detect?access_token={}'.format(token)
        headers = {'content-type': 'application/json'}
        params = {"image": data,
                "image_type": "BASE64",
                "face_field": "age,beauty,expression,face_shape,gender,glasses,"
                                "quality,eye_status,emotion,face_type,mask,spoofing"}
        res = requests.post(url, headers=headers, data=params)
        if res.status_code == 200:
            return res.json()


    def getData(self, img):
        try:
            data = self.appearance(self.encode(img), self.token)
            face_info = data["result"]['face_list'][0]
            return data
        except Exception as e:
            print(e)
            print("未识别到人脸")
            return -1


# if __name__ == "__main__":
#     data = appearance(encode("../test.png"), access_token(app_key, app_secret))
#     print(data)